package com.example.zyedu.fragment.Report;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zyedu.R;
import com.example.zyedu.adapter.Reportadapter;
import com.example.zyedu.base.BaseFragment;
import com.example.zyedu.entity.Bean;
import com.example.zyedu.entity.ReportBean;
import com.example.zyedu.tools.L;
import com.example.zyedu.view.ClassDateView;
import com.google.gson.Gson;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by acer on 2017/8/4.
 */

public class ReportFragment extends BaseFragment<ReportPresenter, ReportModlel> implements ReportContract.View, PopupMenu.OnMenuItemClickListener {
    ClassDateView report_class;
    ArrayList<String> report_date;
    ListView listView;
    ArrayList<Integer> item;
    private PopupMenu pop;
    TextView report_selclass;
    ImageView report_classselect;
    Button report_submit;
    Reportadapter re;
    ReportBean reportbean;
    String str;
    Date curDate;
    Bean<ReportBean> bean;
    TextView rep_title_remark;
    @Override
    protected void init() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_in_report;
    }

    @Override
    public void initView() {
        // TODO: 2017/8/11 初始化控件
        report_class = (ClassDateView) getActivity().findViewById(R.id.report_class);
        listView = (ListView) getActivity().findViewById(R.id.report_lv);
        report_date = new ArrayList<>();
        re = new Reportadapter(context, report_date, report_class);
        listView.setAdapter(re);
        report_selclass = (TextView) getActivity().findViewById(R.id.report_selclass);
        rep_title_remark= (TextView) getActivity().findViewById(R.id.rep_title_remark);
        report_classselect = (ImageView) getActivity().findViewById(R.id.report_classselect);
        report_classselect.setOnClickListener(this);
        report_submit = (Button) getActivity().findViewById(R.id.report_submit);
        report_submit.setOnClickListener(this);
        //TODO 模拟请求当月数据
        final List<DayFinish> list = new ArrayList<>();
        for (int i = 1; i < 32; i++) {
            list.add(new DayFinish(i, 0, 3));
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
        curDate = new Date(System.currentTimeMillis());//获取当前时间
        str = formatter.format(curDate);
        if(str.substring(0,7).equals(spTools.getString("reporttime"))){
        rep_title_remark.setText("(已填报当月课时，再次提交进行修改)");}
        report_class.setRenwu(str, list);
        report_class.setOnClickListener(new ClassDateView.onClickListener() {
            @Override
            public void onLeftRowClick(String month) {
                //Toast.makeText(getActivity(), "点击减箭头", Toast.LENGTH_SHORT).show();
                if (Integer.parseInt(month.substring(5, 7)) == Integer.parseInt(str.substring(5, 7)) && Integer.parseInt(str.substring(8, 10)) <= 10) {
                    report_date.clear();
                    re.notifyDataSetChanged();
                    report_class.monthChange(-1);
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        report_class.setRenwu(list);
                                    }
                                });
                            } catch (Exception e) {
                            }
                        }
                    }.start();
                } else {
                    new AlertDialog.Builder(context).setTitle("提示").setMessage("上月课时上报已结束").setNeutralButton("确定", null).show();
                }
            }

            @Override
            public void onRightRowClick(String month) {
                //Toast.makeText(getActivity(), "点击加箭头", Toast.LENGTH_SHORT).show();
                if (Integer.parseInt(month.substring(5, 7)) == Integer.parseInt(str.substring(5, 7)) - 1) {
                    report_date.clear();
                    re.notifyDataSetChanged();
                    report_class.monthChange(1);
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(1000);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        report_class.setRenwu(list);
                                    }
                                });
                            } catch (Exception e) {
                            }
                        }
                    }.start();
                } else {
                    new AlertDialog.Builder(context).setTitle("提示").setMessage("下月课时上报未开启").setNeutralButton("确定", null).show();
                }
            }

            @Override
            public void onTitleClick(String monthStr, Date month) {
                //Toast.makeText(getActivity(), "点击了标题：" + monthStr, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onWeekClick(int weekIndex, String weekStr) {
                //Toast.makeText(getActivity(), "点击了星期：" + weekStr, Toast.LENGTH_SHORT).show();
            }

            // TODO: 2017/8/11 点击日历动态添加列表项
            @Override
            public void onDayClick(int day, String dayStr, DayFinish finish) {
                //Toast.makeText(getActivity(), "点击了日期：" + dayStr, Toast.LENGTH_SHORT).show();
                Log.w("", "点击了日期:" + dayStr);
                report_date.add(dayStr);
                Collections.sort(report_date);
                re.notifyDataSetChanged();
            }

            // TODO: 2017/8/11 点击日历动态删除列表项
            @Override
            public void onDeleClick(String date) {
                for (int i = 0; i < report_date.size(); i++) {
                    if (report_date.get(i).equals(date)) {
                        report_date.remove(i);
                        re.notifyDataSetChanged();
                        break;
                    }
                }
            }
        });
    }

    // TODO: 2017/8/11  提交课时报表的单击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.report_submit:

                if(report_selclass.getText().toString().equals("")){
                    new AlertDialog.Builder(context).setTitle("提示").setMessage("请添加课程名").setNeutralButton("确定", null).show();
                }else if (report_date.size() == 0) {
                    new AlertDialog.Builder(context).setTitle("提示").setMessage("请添加上报课时").setNeutralButton("确定", null).show();
                } else {
                    reportbean = new ReportBean();
                    TextView report_selclass =
                            (TextView) getActivity().findViewById(R.id.report_selclass);
                    reportbean.setCourse(report_selclass.getText().toString());
                    for (int i = 0; i < report_date.size(); i++) {
                        String date = report_date.get(i);
                        CheckBox report_moning =
                                (CheckBox) listView.getChildAt(i).findViewById(R.id.report_moning);
                        CheckBox report_afternoon =
                                (CheckBox) listView.getChildAt(i).findViewById(R.id.report_afternoon);
                        CheckBox report_night =
                                (CheckBox) listView.getChildAt(i).findViewById(R.id.report_night);
                        reportbean.add(date,
                                report_moning.isChecked() ? "1" : "0"
                                , report_afternoon.isChecked() ? "1" : "0"
                                , report_night.isChecked() ? "1" : "0");
                    }
                    Log.i("1", "ss" + new Gson().toJson(new Bean<ReportBean>(context).addDate(reportbean)));
                    presenter.reportclass(new Bean<ReportBean>(context).addDate(reportbean));

                }
                break;
            // TODO: 2017/8/11 课程选择单击事件 
            case R.id.report_classselect:
                pop = new PopupMenu(context, v);
                pop.setOnMenuItemClickListener(this);
                pop.getMenuInflater()
                        .inflate(R.menu.daily_class_name_meun, pop.getMenu());
                pop.show();
                break;
        }

    }

    // TODO: 2017/8/11 课程选择下拉菜单单击事件 
    @Override
    public boolean onMenuItemClick(MenuItem item) {
            report_selclass.setText(item.getTitle().toString());
        return false;
    }

    @Override
    public void reportSuccess() {
        spTools.setString("reporttime",report_date.get(0).substring(0,7));
        new AlertDialog
                .Builder(context)
                .setTitle("提示")
                .setMessage("提交成功")
                .setNeutralButton("确定", null)
                .show();
        if(str.substring(0,7).equals(spTools.getString("reporttime"))){
            rep_title_remark.setText("(已填报当月课时，再次提交进行修改)");}
        report_date.clear();
        re.notifyDataSetChanged();
        Arrays.fill(report_class.selectday,0);
        report_class.invalidate();

        L.i("1", "Success");
    }

    @Override
    public void reportFail() {
        new AlertDialog
                .Builder(context)
                .setTitle("提示")
                .setMessage("提交失败")
                .setNeutralButton("确定", null)
                .show();
        L.i("1", "Fail");
    }

    public class DayFinish {
        public int day;
        public int all;
        public int finish;

        public DayFinish(int day, int finish, int all) {
            this.day = day;
            this.all = all;
            this.finish = finish;
        }
    }


}
